<script setup lang="ts">
import type { DataField, DataFieldOption } from '.'
import { storeToRefs } from 'pinia'
import { computed, onMounted } from 'vue'
import { useDictStore } from '@/stores/dictStore'

const { row, field } = defineProps<{
  row: any
  field: DataField
}>()

const dictCode = (typeof field.dict === 'string') ? field.dict : field.dict?.dictCode

const dictStore = useDictStore()
const { dictMap } = storeToRefs(dictStore)

onMounted(async () => {
  if (dictCode) {
    await dictStore.loadDict(dictCode)
  }
})

const option = computed<DataFieldOption | undefined>(() => {
  if (dictCode && dictMap.value[dictCode]) {
    const dicts = dictStore.flatDicts(dictCode)
    const result = dicts
      .map((d): DataFieldOption => {
        return {
          value: d.dictCode!,
          label: d.dictName!,
          tagType: d.valueType === 'CUSTOM' ? d.customData?.tagType : undefined,
          tagColor: d.valueType === 'CUSTOM' ? d.customData?.tagColor : undefined,
        }
      })
      .find(o => o.value === row[field.name])
    return result
  }
  else {
    return field.options?.find(o => o.value === row[field.name])
  }
})
</script>

<template>
  <template v-if="option">
    <el-tag v-if="option?.tagType || option?.tagColor" :type="option.tagType" :color="option.tagColor" effect="dark" round>
      {{ option.label }}
    </el-tag>
    <template v-else>
      {{ option.label }}
    </template>
  </template>
  <el-link v-else-if="field.click !== undefined" type="primary" underline="never" @click="field.click(row) ">
    {{ row[field.name] }}
  </el-link>
  <template v-else-if="row[field.name] !== undefined && field.type === 'boolean'">
    {{ row[field.name] === true ? '是' : '否' }}
  </template>

  <template v-else>
    {{ row[field.name] }}
  </template>
</template>
